import logging

from django.shortcuts import render

from rest_framework.views import APIView
import random
from django_redis import get_redis_connection
from django.core.mail import send_mail
from rest_framework.response import Response
from rest_framework import status
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')


def ValueCode():
    randomStr = ''
    for i in range(4):
        dig = str(random.randint(0, 9))
        low = chr(random.randint(97, 122))
        up = chr(random.randint(65, 90))
        code = random.choice([dig, low, up])
        randomStr += code
    return randomStr


class SMSCodeView(APIView):
    """发送邮箱验证码"""

    def get(self, request, email):
        redis_conn = get_redis_connection('mailcodes')
        em = email.split("@")[0]  # 分割邮箱获取@前面的字符串
        # 先从 redis获取 标记
        send_flag = redis_conn.get(f'send_flag_{em}')
        # 如果取到了标记，说明该邮箱已经发送
        if send_flag:
            return Response({'message': '邮箱重复发送'}, status=status.HTTP_400_BAD_REQUEST)
        # 生成邮箱验证码
        code = ValueCode()
        logger.info(code)
        # redis管道技术：将多次redis操作放到管道中，一次性执行，减少redis连接次数，提高性能
        pl = redis_conn.pipeline()
        # redis缓存验证码
        pl.setex(f'mail_{em}', 300, code)  # 存储成字符串格式, 键(唯一)， 300s过期时间，
        # 存储一个标记  -- 限制同一个邮箱60s内只能发送一次
        pl.setex(f'send_flag_{em}', 60, 1)
        # 把验证码通过qq
        EMAIL_FROM = "Itlaity@qq.com"  # 邮箱来自
        email_title = '邮箱激活'
        email_body = "您的邮箱注册验证码为：{0}, 该验证码有效时间为两分钟，请及时进行验证。".format(code)
        # 执行管道
        pl.execute()
        # 响应
        try:
            # send_status = send_mail(email_title, email_body, EMAIL_FROM, ['wws__qln@163.com'])
            # send_mail(email_title, email_body, EMAIL_FROM, [email])
            # 添加到celery异步任务队列
            # send_sms_code(email_title, email_body, EMAIL_FROM, email)
            send_sms_code.delay(email_title, email_body, EMAIL_FROM, email)

        except Exception as e:
            print(e)
        return Response({'message': 'ok'})
